﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace HRdex_Final.Message
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //string msg = Request.QueryString["MessegeSenderID"];
            string msg = (string)(Session["messageID"]);
            //string snt = (string)(Session["sentID"]);
            string snt = (string)(Session["sent"]);
            string nu = (string)(Session["new"]);
            //txtFrom.Text = SessionID();

            if (msg != null && nu == "1")
            {

                string sqlc = "SELECT  formMessegeSender.Subject, formMessegeSender.Description, formMessegeSender.DateTime," +
                " formEmployees.LastName + ', ' + formEmployees.FirstName AS fulname, catMessege.catMessegeName, " +
                "formMessegeSender.fromEmpID, formMessegeSender.AttachmentName, formMessegeSender.Readed " +
                "FROM  formMessegeSender INNER JOIN formEmployees ON formMessegeSender.EmployeeID = formEmployees.EmployeeID " +
                "INNER JOIN catMessege ON formMessegeSender.catMessegeID = catMessege.catMessegeID " +
                "WHERE (formMessegeSender.MessageID = " + msg + ")";

                SqlDataAdapter cmd = new SqlDataAdapter(sqlc, conn);

                cmd.Fill(dtbl);
                lblFrom.Text = dtbl.Rows[0].ItemArray[3].ToString();
                lblTo.Text = dtbl.Rows[0].ItemArray[5].ToString();
                lblSubject.Text = dtbl.Rows[0].ItemArray[0].ToString();
                lblDescription.Text = dtbl.Rows[0].ItemArray[1].ToString();
                //lblAttach.Text = dtbl.Rows[0].ItemArray[2].ToString();
                lblPubDate.Text = dtbl.Rows[0].ItemArray[2].ToString();
                lblType.Text = dtbl.Rows[0].ItemArray[4].ToString();
                if (dtbl.Rows[0][6] == null)
                {
                    lblAttach.Visible = false;
                }

                if (snt == null)
                {
                    if (dtbl.Rows[0][7].ToString() != "1")
                    {
                        sqlc = "UPDATE formMessegeSender SET  Readed = 1 WHERE MessageID = " + msg;
                        sqlexecute(sqlc);
                        Session["sent"] = null;
                    }
                }
                Session["new"] = null;

            }

            //else if (snt != null)
            //{
            //    string sqlc = "SELECT  formMessegeSender.Subject, formMessegeSender.Description, formMessegeSender.DateTime," +
            //    " formEmployees.LastName + ', ' + formEmployees.FirstName AS fulname, catMessege.catMessegeName, formMessegeSender.EmployeeID, formMessegeSender.AttachmentName " +
            //    "FROM  formMessegeSender INNER JOIN formEmployees ON formMessegeSender.EmployeeID = formEmployees.EmployeeID " +
            //    "INNER JOIN catMessege ON formMessegeSender.catMessegeID = catMessege.catMessegeID " +
            //    "WHERE (formMessegeSender.fromEmpID = " + snt + ")";

            //    SqlDataAdapter cmd = new SqlDataAdapter(sqlc, conn);

            //    cmd.Fill(dtbl);
            //    lblFrom.Text = dtbl.Rows[0].ItemArray[3].ToString();
            //    lblTo.Text = dtbl.Rows[0].ItemArray[5].ToString();
            //    lblSubject.Text = dtbl.Rows[0].ItemArray[0].ToString();
            //    lblDescription.Text = dtbl.Rows[0].ItemArray[1].ToString();
            //    //lblAttach.Text = dtbl.Rows[0].ItemArray[2].ToString();
            //    lblPubDate.Text = dtbl.Rows[0].ItemArray[2].ToString();
            //    lblType.Text = dtbl.Rows[0].ItemArray[4].ToString();
            //    if (dtbl.Rows[0][6].ToString() == null)
            //    {
            //        lblAttach.Visible = false;
            //    }
            //}
            else
            {
                pnlCreate.Visible = true;
                pnlRead.Visible = false;
                btnDelete.Visible = false;
                btnForward.Visible = false;
                btnReply.Visible = false;

            }
            
        }
        DataTable dtbl = new DataTable();
        SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\HRdexDB.mdf;Integrated Security=True;User Instance=True");
        

        protected void txtSubmit_Click1(object sender, EventArgs e)
        {
            string filepath = fuAttachment.PostedFile.FileName;
            string flname = Path.GetFileName(filepath);
            string sqlc;

            if (flname != null)
            {
                sqlc = "INSERT INTO formMessegeSender (Subject, Description, DateTime, EmployeeID, catMessegeID, fromEmpID, Readed, AttachmentName, AttachmentData) " +
                    "VALUES (@subj, @desc,  @datetime, @empID, @catMsg, @fromEmpID, 0 ,@attachname,@attachment)";
            }
            else
	        {
                sqlc = "Insert Into formMessegeSender (Subject, Description, DateTime, EmployeeID, catMessegeID, fromEmpID, Readed) " +
                "Values (@subj, @desc,  @datetime, @empID, @catMsg, @fromEmpID, 0)";
	        }

            SqlDataAdapter adapter = new SqlDataAdapter();
            
            //DataSet ds = new DataSet();

            conn.Open();

            SqlCommand cmd = new SqlCommand(sqlc, conn);

            Stream fs = fuAttachment.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
            //fuAttachment.PostedFile.FileName;
            

            cmd.Parameters.Add("@subj", SqlDbType.VarChar).Value = txtSubject.Text;
            cmd.Parameters.Add("@desc", SqlDbType.VarChar).Value = txtBody.Text;
            cmd.Parameters.Add("@datetime", SqlDbType.VarChar).Value = DateTime.Now;
            cmd.Parameters.Add("@empID", SqlDbType.Int).Value = ddlToSend.SelectedValue;
           
            cmd.Parameters.Add("@catMsg", SqlDbType.Int).Value = ddlCategory.Text;
            cmd.Parameters.Add("@fromEmpID", SqlDbType.VarChar).Value = SessionID();
            if (flname != null)
            {
                cmd.Parameters.Add("@attachment", SqlDbType.VarBinary).Value = bytes;
                cmd.Parameters.Add("@attachname", SqlDbType.NChar).Value = flname;
            }

            int sntchk = cmd.ExecuteNonQuery();

            if (sntchk != 0)
            {
                lblsent.Visible = true;
                txtBody.Text = null;
                txtSubject.Text = null;
            }

            conn.Close();
        }

        //override protected void OnInit(EventArgs e)
        //{
        //    InitializeComponent();
        //    base.OnInit(e);
        //}

        //private void InitializeComponent()
        //{
        //    //this.cmdStore.Click += new System.EventHandler(this.cmdStore_Click);
        //    this.Load += new System.EventHandler(this.Page_Load);
        //}

        string SessionID()
        {
            return Session["EmployeeID"].ToString();
        }

        protected void lblAttach_Click(object sender, EventArgs e)
        {
            string msg = (string)(Session["messageID"]);
            string strQuery = "SELECT AttachmentData, AttachmentName FROM formMessegeSender WHERE MessageID = " + msg;
            SqlCommand cmd = new SqlCommand(strQuery);
            DataTable dt = GetData(cmd);
            if (dt != null)
            {
                download(dt);
            }
        }

        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            try
            {
                conn.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;

            }
            catch
            {
                return null;
            }
            finally
            {
                conn.Close();
                sda.Dispose();
                conn.Dispose();
            }

        }
        private void download(DataTable dt)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["AttachmentData"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //Response.ContentType = dt.Rows[0]["FileType"].ToString();
            Response.AddHeader("content-disposition", "attachment;FileName="
            + dt.Rows[0]["AttachmentName"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            string msg = (string)(Session["messageID"]);
            string del = "DELETE FROM formMessegeSender WHERE MessageID = " + msg;
            sqlexecute(del);
            Server.Transfer("~/Message/ReceivedItems.aspx");
        }
        void sqlexecute(string sqlcmd)
        {
            SqlCommand cmd = new SqlCommand(sqlcmd, conn);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                //throw;
            }
            finally
            {
                conn.Close();
            }

        }

        protected void btnForward_Click(object sender, ImageClickEventArgs e)
        {
            txtBody.Text = lblDescription.Text;
            //ddlCategory.ClearSelection();
            //ddlCategory.Items.FindByText(lblType.Text).Selected = true;
            txtSubject.Text = lblSubject.Text;
            //txtFrom.Text = lblFrom.Text;

            string msg = (string)(Session["messageID"]);

            string sqlc = "SELECT  catMessegeID FROM formMessegeSender WHERE (MessageID = " + msg + ")";
            SqlDataAdapter cmd = new SqlDataAdapter(sqlc, conn);
            DataTable tbl = new DataTable();
            cmd.Fill(tbl);

            string msgtype = tbl.Rows[0][0].ToString();
            ddlCategory.SelectedValue = msgtype;

            pnlCreate.Visible = true;
            pnlRead.Visible = false;
            btnDelete.Visible = false;
            btnForward.Visible = false;
            btnReply.Visible = false;
        }

        protected void btnReply_Click(object sender, ImageClickEventArgs e)
        {
            //ddlToSend.ClearSelection();
            //ddlToSend.Items.FindByText(lblTo.Text).Selected = true;
            //txtFrom.Text = lblFrom.Text;

            string msg = (string)(Session["messageID"]);

            string sqlc = "SELECT  EmployeeID FROM formMessegeSender WHERE MessageID = " + msg;
            SqlDataAdapter cmd = new SqlDataAdapter(sqlc, conn);
            DataTable tbl = new DataTable();
            cmd.Fill(tbl);
            string msgreply = tbl.Rows[0][0].ToString();
            ddlCategory.SelectedValue = msgreply;

            pnlCreate.Visible = true;
            pnlRead.Visible = false;
            btnDelete.Visible = false;
            btnForward.Visible = false;
            btnReply.Visible = false;
        }

        protected void txtCancel_Click(object sender, EventArgs e)
        {
            txtBody.Text = null;
            txtSubject.Text = null;
        }
    }
}